<?php
session_start();
ini_set('disable_functions', 'exec,system,passthru,shell_exec,proc_open,popen,curl_exec,parse_ini_file,show_source,file_get_contents,fopen,file_put_contents,unlink,rmdir,rename,copy,chmod');
include_once __DIR__ . '/mute_handler.php';
if (!isset($_SESSION['username'])) {
    header('Location: login.php');
    exit();
}

require_once 'track_online.php';
require_once 'auto_join_group.php'; autoJoinGroup($_SESSION['username'], $_GET['group_name']);
$currentUser = $_SESSION['username'];
$groupId = $_GET['id'] ?? null;
$groupExists = false;
$groupName = '未知群聊';
// 读取称号配置文件
$titlesFile = __DIR__ . '/ch.json';
$allTitles = [];
if (file_exists($titlesFile)) {
    $allTitles = json_decode(file_get_contents($titlesFile), true) ?: [];
}
// 检查群聊ID的有效性
if ($groupId) {
    $groupInfoFile = __DIR__ . "/ql/info.json";
    
    if (file_exists($groupInfoFile)) {
        $groups = json_decode(file_get_contents($groupInfoFile), true);
        
        if (isset($groups[$groupId])) {
            $groupExists = true;
            $groupName = $groups[$groupId]['name'] ?? '未知群聊';
        }
    }
}

// 获取当前用户信息
$userInfoFile = __DIR__ . "/user/$currentUser/info.json";
$userAvatar = 'default-avatar.png';

if (file_exists($userInfoFile)) {
    $userInfo = json_decode(file_get_contents($userInfoFile), true);
    $userAvatar = $userInfo['avatar'] ?? $userAvatar;
}

// 处理请求 - 仅当群聊存在时
if ($groupExists && $_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = $_POST['action'] ?? null;
    $groupChatFile = __DIR__ . "/ql/$groupId/messages.json";

    // 确保消息文件存在
    if (!file_exists($groupChatFile)) {
        file_put_contents($groupChatFile, json_encode([]));
    }

    // 发送文字消息
    if ($action === 'send_message') {
        $message = trim($_POST['message']);
        if (empty($message) || mb_strlen($message, 'UTF-8') > 2000) {
            echo json_encode(['status' => 'error', 'message' => '消息不能为空或超过2000个字符！']);
            exit();
        }

        $messages = json_decode(file_get_contents($groupChatFile), true) ?: [];
        $messages[] = [
            'id' => uniqid(),
            'sender' => $currentUser,
            'avatar' => $userAvatar,
            'content' => htmlspecialchars($message),
            'type' => 'text',
            'timestamp' => date('Y-m-d H:i:s'),
        ];
        file_put_contents($groupChatFile, json_encode($messages));
        echo json_encode(['status' => 'success']);
        exit();
    }

    // 发送图片消息
    if ($action === 'send_image' && isset($_FILES['image']) && $_FILES['image']['error'] === UPLOAD_ERR_OK) {
        $uploadsDir = __DIR__ . "/ql/$groupId/uploads";
        if (!is_dir($uploadsDir)) {
            mkdir($uploadsDir, 0777, true);
        }

        $imageName = uniqid() . '_' . basename($_FILES['image']['name']);
        $imagePath = $uploadsDir . '/' . $imageName;
        
        if (move_uploaded_file($_FILES['image']['tmp_name'], $imagePath)) {
            $messages = json_decode(file_get_contents($groupChatFile), true) ?: [];
            $messages[] = [
                'id' => uniqid(),
                'sender' => $currentUser,
                'avatar' => $userAvatar,
                'content' => "ql/$groupId/uploads/$imageName",
                'type' => 'image',
                'timestamp' => date('Y-m-d H:i:s'),
            ];
            file_put_contents($groupChatFile, json_encode($messages));
            echo json_encode(['status' => 'success']);
            exit();
        } else {
            echo json_encode(['status' => 'error', 'message' => '图片上传失败']);
            exit();
        }
    }

    // 重新发送失败的消息
    if ($action === 'retry_message' && isset($_POST['message_id'])) {
        $messageId = $_POST['message_id'];
        $messages = json_decode(file_get_contents($groupChatFile), true) ?: [];
        
        // 查找消息
        $messageIndex = array_search($messageId, array_column($messages, 'id'));
        
        if ($messageIndex !== false) {
            $message = $messages[$messageIndex];
            
            // 重新添加到消息列表（模拟重新发送）
            $messages[] = [
                'id' => uniqid(),
                'sender' => $currentUser,
                'avatar' => $userAvatar,
                'content' => $message['content'],
                'type' => $message['type'],
                'timestamp' => date('Y-m-d H:i:s'),
            ];
            
            file_put_contents($groupChatFile, json_encode($messages));
            echo json_encode(['status' => 'success']);
            exit();
        }
        
        echo json_encode(['status' => 'error', 'message' => '消息不存在']);
        exit();
    }

    echo json_encode(['status' => 'error', 'message' => '无效的操作！']);
    exit();
}

// 获取消息 - 仅当群聊存在时
if ($groupExists && $_SERVER['REQUEST_METHOD'] === 'GET' && isset($_GET['fetch_messages'])) {
    $groupChatFile = __DIR__ . "/ql/$groupId/messages.json";
    
    if (!file_exists($groupChatFile)) {
        echo json_encode([]);
        exit();
    }
    
    $messages = json_decode(file_get_contents($groupChatFile), true) ?: [];
    
    // 添加时间戳用于避免消息重复
    foreach ($messages as &$msg) {
        if (!isset($msg['timestamp'])) {
            $msg['timestamp'] = time();
        }
    }
    
    echo json_encode($messages);
    exit();
}
?>
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><?= $groupExists ? htmlspecialchars($groupName) : '群聊不存在' ?></title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twemoji/14.0.2/twemoji.min.css">
<style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, 'Open Sans', 'Helvetica Neue', sans-serif;
            -webkit-tap-highlight-color: transparent;
        }
        
        body {
            background-color: #f0f2f5;
            color: #333;
            height: 100vh;
            overflow: hidden;
        }
        
        /* 导航栏 */
        .navbar {
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            background: linear-gradient(135deg, #1a2a6c, #2a5298);
            color: white;
            padding: 12px 15px;
            display: flex;
            align-items: center;
            box-shadow: 0 2px 12px rgba(0,0,0,0.15);
            z-index: 100;
        }
        
        .back-btn {
            background: rgba(255,255,255,0.15);
            border: none;
            color: white;
            font-size: 18px;
            margin-right: 12px;
            cursor: pointer;
            width: 40px;
            height: 40px;
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            transition: background 0.3s;
        }
        
        .back-btn:hover {
            background: rgba(255,255,255,0.25);
        }
        
        .navbar-title {
            font-size: 18px;
            font-weight: 600;
            flex-grow: 1;
        }
        
        .tools-btn {
            background: rgba(255,255,255,0.15);
            border: none;
            color: white;
            width: 40px;
            height: 40px;
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            cursor: pointer;
            transition: background 0.3s;
        }
        
        .tools-btn:hover {
            background: rgba(255,255,255,0.25);
        }
        
        /* 聊天容器 */
        #chat-container {
            position: relative;
            margin-top: 64px;
            margin-bottom: 80px;
            padding: 15px 12px 5px;
            height: calc(100vh - 144px);
            overflow-y: auto;
            scroll-behavior: smooth;
            display: flex;
            flex-direction: column;
            align-items: stretch;
        }
        
        .no-messages {
            text-align: center;
            padding: 60px 20px;
            color: #7f8c8d;
            font-size: 16px;
        }
        
        /* 消息样式 - 清晰简明的布局 */
        .message-group {
            margin-bottom: 16px;
            max-width: 85%;
            align-self: flex-start;
        }
        
        .message-group.current-user {
            align-self: flex-end;
        }
        
        .message-container {
            display: flex;
            align-items: flex-start;
            gap: 10px;
            margin-bottom: 8px;
        }
        
        .current-user .message-container {
            flex-direction: row-reverse;
        }
        
        .avatar {
            width: 38px;
            height: 38px;
            border-radius: 50%;
            background: linear-gradient(135deg, #3498db, #2c3e50);
            object-fit: cover;
            flex-shrink: 0;
            display: flex;
            align-items: center;
            justify-content: center;
            color: white;
            font-weight: bold;
            font-size: 18px;
        }
        
        .message-content-wrapper {
            max-width: calc(100% - 50px);
            min-width: 100px;
        }
        
        .message-header {
            display: flex;
            align-items: baseline;
            margin-bottom: 5px;
        }
        
        .username {
            font-weight: 600;
            font-size: 14px;
            color: #2d3748;
            margin-right: 8px; /* 在用户名和称号之间添加间距 */
            flex-shrink: 0; /* 防止用户名被压缩 */
        }
        
        .current-user .username {
            color: #3a86ff;
            text-align: right;
        }
        
        .timestamp {
            font-size: 11px;
            color: #718096;
            margin-left: 8px;
        }
        
        .current-user .timestamp {
            margin-left: 0;
            margin-right: 8px;
            color: #7f8c8d;
        }
        
        .message-content {
            background: #ffffff;
            padding: 12px 15px;
            border-radius: 16px;
            border-bottom-left-radius: 4px;
            box-shadow: 0 2px 6px rgba(0,0,0,0.05);
            word-wrap: break-word;
            line-height: 1.5;
            position: relative;
        }
        
        .current-user .message-content {
            background: linear-gradient(135deg, #3a86ff, #2667ff);
            color: white;
            border-bottom-right-radius: 4px;
            border-bottom-left-radius: 16px;
        }
        
        .message-image {
            max-width: 260px;
            max-height: 260px;
            border-radius: 12px;
            box-shadow: 0 3px 8px rgba(0,0,0,0.1);
            cursor: pointer;
            display: block;
        }
        
        /* 消息状态指示器 */
        .message-status {
            position: absolute;
            bottom: -18px;
            right: 8px;
            font-size: 11px;
            display: flex;
            align-items: center;
            color: #718096;
        }
        
        .current-user .message-status {
            right: auto;
            left: 8px;
        }
        
        .message.sending .message-status {
            color: #718096;
        }
        
        .message.failed .message-status {
            color: #e74c3c;
        }
        
        /* 重发按钮 */
        .retry-btn {
            display: inline-flex;
            align-items: center;
            background: none;
            border: none;
            cursor: pointer;
            padding: 2px 6px;
            font-size: 11px;
            margin-left: 5px;
            color: #e74c3c;
            font-weight: 500;
        }
        
        .retry-btn:hover {
            text-decoration: underline;
        }
        
        /* 图片预览 */
        #preview {
            position: fixed;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            background: rgba(0, 0, 0, 0.95);
            display: none;
            justify-content: center;
            align-items: center;
            z-index: 1000;
        }
        
        #preview img {
            max-width: 90%;
            max-height: 90%;
            border-radius: 12px;
            box-shadow: 0 15px 50px rgba(0,0,0,0.3);
        }
        
        .preview-controls {
            position: absolute;
            top: 20px;
            right: 20px;
        }
        
        .close-btn {
            background: rgba(255,255,255,0.1);
            color: white;
            border: none;
            width: 50px;
            height: 50px;
            border-radius: 50%;
            font-size: 24px;
            cursor: pointer;
            display: flex;
            align-items: center;
            justify-content: center;
            transition: background 0.3s;
        }
        
        .close-btn:hover {
            background: rgba(255,255,255,0.2);
        }
        
        /* 滚动到底部按钮 */
        .scroll-to-bottom {
            position: fixed;
            bottom: 100px;
            right: 20px;
            width: 46px;
            height: 46px;
            border-radius: 50%;
            background: linear-gradient(135deg, #3498db, #2980b9);
            color: white;
            border: none;
            box-shadow: 0 3px 12px rgba(0,0,0,0.15);
            cursor: pointer;
            display: none;
            align-items: center;
            justify-content: center;
            font-size: 18px;
            z-index: 90;
            opacity: 0.9;
            transition: all 0.3s;
        }
        
        .scroll-to-bottom:hover {
            opacity: 1;
            transform: translateY(-3px);
        }
        
        /* 输入区域 */
        #chat-input-container {
            position: fixed;
            bottom: 0;
            left: 0;
            right: 0;
            background: white;
            padding: 12px 15px;
            box-shadow: 0 -2px 12px rgba(0,0,0,0.1);
            z-index: 100;
        }
        
        #message-form {
            display: flex;
            align-items: flex-end;
            gap: 8px;
        }
        
        .input-wrapper {
            flex: 1;
            position: relative;
            background: #f0f2f5;
            border-radius: 25px;
        }
        
        #message-input {
            width: 100%;
            padding: 14px 20px;
            border: none;
            background: transparent;
            font-size: 15px;
            resize: none;
            max-height: 150px;
            overflow-y: auto;
            border-radius: 25px;
        }
        
        #message-input:focus {
            outline: none;
        }
        
        #char-counter {
            position: absolute;
            bottom: 6px;
            right: 20px;
            font-size: 11px;
            color: #a0aec0;
            background: rgba(255,255,255,0.8);
            padding: 3px 8px;
            border-radius: 10px;
        }
        
        /* 按钮样式 */
        .btn-emoji, .btn-image, .btn-send {
            border: none;
            width: 46px;
            height: 46px;
            border-radius: 50%;
            font-size: 18px;
            cursor: pointer;
            display: flex;
            align-items: center;
            justify-content: center;
            transition: transform 0.2s, background 0.3s;
        }
        
        .btn-emoji {
            background: #f39c12;
            color: white;
        }
        
        .btn-emoji:hover {
            background: #e67e22;
        }
        
        .btn-image {
            background: #2ecc71;
            color: white;
        }
        
        .btn-image:hover {
            background: #27ae60;
        }
        
        .btn-send {
            background: #3498db;
            color: white;
        }
        
        .btn-send:hover {
            background: #2980b9;
        }
        
        .btn-send:disabled {
            background: #cbd5e0;
            cursor: not-allowed;
            transform: none !important;
        }
        
        /* 表情选择器 */
        #emoji-picker {
            position: fixed;
            bottom: 80px;
            left: 0;
            width: 100%;
            height: 200px;
            background: white;
            box-shadow: 0 -5px 15px rgba(0,0,0,0.1);
            display: none;
            flex-wrap: wrap;
            justify-content: center;
            align-content: flex-start;
            overflow-y: auto;
            padding: 15px;
            z-index: 100;
        }
        
        .emoji-item {
            font-size: 26px;
            width: 38px;
            height: 38px;
            display: flex;
            align-items: center;
            justify-content: center;
            cursor: pointer;
            border-radius: 8px;
            margin: 3px;
            transition: background 0.2s;
        }
        
        .emoji-item:hover {
            background: #f0f7ff;
        }
        
        /* 动画 */
        @keyframes spin {
            from { transform: rotate(0deg); }
            to { transform: rotate(360deg); }
        }
        
        @keyframes fadeIn {
            from { opacity: 0; transform: translateY(8px); }
            to { opacity: 1; transform: translateY(0); }
        }
        
        .fade-in {
            animation: fadeIn 0.3s ease-out;
        }
        
        /* 响应式调整 */
        @media (max-width: 768px) {
            .navbar {
                padding: 10px 12px;
            }
            
            .navbar-title {
                font-size: 16px;
            }
            
            #chat-container {
                margin-top: 60px;
                padding: 12px 10px;
            }
            
            .message-group {
                max-width: 90%;
            }
            
            .avatar {
                width: 36px;
                height: 36px;
            }
            
            .btn-emoji, .btn-image, .btn-send {
                width: 40px;
                height: 40px;
                font-size: 16px;
            }
            
            #emoji-picker {
                height: 170px;
            }
        }
        .error-container {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    height: 100vh;
    padding: 20px;
    text-align: center;
    background: linear-gradient(135deg, #f5f7fa, #e4e7eb);
}

.error-icon {
    font-size: 80px;
    color: #e74c3c;
    margin-bottom: 20px;
}

.error-container h1 {
    font-size: 28px;
    color: #2d3748;
    margin-bottom: 15px;
}

.error-container p {
    font-size: 18px;
    color: #4a5568;
    max-width: 600px;
    margin-bottom: 30px;
    line-height: 1.6;
}

.action-buttons {
    display: flex;
    gap: 15px;
    flex-wrap: wrap;
    justify-content: center;
}

.btn-home, .btn-join, .btn-leave {
    padding: 12px 25px;
    border-radius: 30px;
    font-size: 16px;
    font-weight: 500;
    cursor: pointer;
    display: flex;
    align-items: center;
    gap: 8px;
    transition: all 0.3s;
    border: none;
    box-shadow: 0 4px 12px rgba(0,0,0,0.1);
}

.btn-home {
    background: linear-gradient(135deg, #3498db, #2980b9);
    color: white;
}

.btn-join {
    background: linear-gradient(135deg, #2ecc71, #27ae60);
    color: white;
}

.btn-leave {
    background: linear-gradient(135deg, #e74c3c, #c0392b);
    color: white;
}

.btn-home:hover {
    transform: translateY(-3px);
    box-shadow: 0 6px 15px rgba(52, 152, 219, 0.4);
}

.btn-join:hover {
    transform: translateY(-3px);
    box-shadow: 0 6px 15px rgba(46, 204, 113, 0.4);
}

.btn-leave:hover {
    transform: translateY(-3px);
    box-shadow: 0 6px 15px rgba(231, 76, 60, 0.4);
}

.btn-home i, .btn-join i, .btn-leave i {
    font-size: 18px;
}
/* 用户称号样式 */
.titles-container {
    display: flex;
    flex-direction: row !important; /* 确保横排显示 */
    gap: 6px;
    flex-wrap: wrap;
    align-items: center;
    max-width: 250px; /* 限制宽度防止溢出 */
}

.user-title {
    display: inline-block;
    padding: 3px 10px;
    border-radius: 15px;
    font-size: 11px;
    font-weight: 600;
    color: white !important;
    box-shadow: 0 2px 5px rgba(0,0,0,0.1);
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
    line-height: 1.3;
    text-align: center;
    transition: transform 0.2s, box-shadow 0.2s;
}

.user-title:hover {
    transform: translateY(-2px);
    box-shadow: 0 4px 8px rgba(0,0,0,0.15);
}

/* 当前用户的消息调整 */
.current-user .titles-container {
    justify-content: flex-end; /* 右对齐 */
    margin-right: 8px; /* 调整右边距 */
}

/* 响应式调整 */
@media (max-width: 768px) {
    .titles-container {
        max-width: 180px;
    }
    
    .user-title {
        font-size: 10px;
        padding: 2px 6px;
    }
}
    </style>
</head>
<body>
    <?php if (!$groupExists): ?>
        <!-- 错误页面 -->
        <div class="error-container">
            <div class="error-icon">
                <i class="fas fa-exclamation-triangle"></i>
            </div>
            <h1>群聊不存在</h1>
            <p>该群聊可能已被解散、封禁或从未存在。请检查群聊ID是否正确。</p>
            <div class="action-buttons">
                <button class="btn-home" onclick="location.href='index.php'">
                    <i class="fas fa-home"></i> 返回首页
                </button>
                <button class="btn-join" onclick="location.href='qljoin.php'">
                    <i class="fas fa-plus-circle"></i> 加入新群聊
                </button>
                <button class="btn-leave" onclick="leaveGroup()">
            <i class="fas fa-sign-out-alt"></i> 退出群聊
        </button>
            </div>
        </div>
    <?php else: ?>
        <!-- 正常群聊页面 -->
        <div class="navbar">
            <button class="back-btn" onclick="history.back()">
                <i class="fas fa-arrow-left"></i>
            </button>
            <div class="navbar-title"><?= htmlspecialchars($groupName) ?></div>
            <button class="tools-btn" onclick="location.href='qlmenu.php?group_id=<?= $groupId ?>&group_name=<?= urlencode($groupName) ?>'">
                <i class="fas fa-cog"></i>
            </button>
        </div>
        
        <div id="chat-container">
            <div class="no-messages" id="loading-messages">
                <i class="fas fa-spinner fa-spin"></i> 正在加载消息...
            </div>
        </div>
        
        <button class="scroll-to-bottom" id="scroll-to-bottom-btn">
            <i class="fas fa-arrow-down"></i>
        </button>
        
        <div id="preview">
            <img src="" alt="图片预览">
            <div class="preview-controls">
                <button class="close-btn" onclick="closePreview()">
                    <i class="fas fa-times"></i>
                </button>
            </div>
        </div>
        
        <div id="emoji-picker">
            <!-- 表情将由JavaScript生成 -->
        </div>
        
        <div id="chat-input-container">
            <form id="message-form">
                <div class="input-wrapper">
                    <textarea id="message-input" placeholder="输入消息..." rows="1"></textarea>
                    <div id="char-counter">0/2000</div>
                </div>
                <input type="file" id="image-input" accept="image/*" style="display: none;">
                <button type="button" class="btn-emoji" id="emoji-btn">
                    <i class="far fa-smile"></i>
                </button>
                <button type="button" class="btn-image" id="image-btn">
                    <i class="fas fa-camera"></i>
                </button>
                <button type="submit" class="btn-send">
                    <i class="fas fa-paper-plane"></i>
                </button>
            </form>
        </div>
    <?php endif; ?>
    
  <script>
    <?php if ($groupExists): ?>
        // 常量和DOM元素定义
        const GROUP_ID = '<?= $groupId ?>';
        const CURRENT_USER = '<?= $currentUser ?>';
        const USER_AVATAR = '<?= $userAvatar ?>';
        
        const chatContainer = document.getElementById('chat-container');
        const messageInput = document.getElementById('message-input');
        const emojiBtn = document.getElementById('emoji-btn');
        const emojiPicker = document.getElementById('emoji-picker');
        const preview = document.getElementById('preview');
        const previewImage = preview.querySelector('img');
        const imageInput = document.getElementById('image-input');
        const imageBtn = document.getElementById('image-btn');
        const sendBtn = document.querySelector('.btn-send');
        const charCounter = document.getElementById('char-counter');
        const scrollToBottomBtn = document.getElementById('scroll-to-bottom-btn');
        const form = document.getElementById('message-form');
        const loadingMessages = document.getElementById('loading-messages');
        
        // 状态变量
        let isLoading = false;
        let isSending = false;
        let isAtBottom = true;
        let isEmojiPickerOpen = false;
        let allMessages = [];
        let renderedMessageIds = new Set();
        const pendingTempMessages = new Map();
        let lastFetchTime = 0;
        let messageCache = new Map(); // 新增消息缓存
        
        // 初始化函数
        function init() {
            initEmojiPicker();
            adjustInputHeight();
            updateCharCounter();
            attachEventListeners();
            fetchMessages();
        }

        // 事件监听器设置
        function attachEventListeners() {
            messageInput.addEventListener('input', handleInputChange);
            form.addEventListener('submit', handleSubmit);
            imageBtn.addEventListener('click', () => imageInput.click());
            imageInput.addEventListener('change', sendImage);
            emojiBtn.addEventListener('click', toggleEmojiPicker);
            document.addEventListener('click', handleDocumentClick);
            chatContainer.addEventListener('scroll', handleScroll);
            scrollToBottomBtn.addEventListener('click', scrollToBottom);
            window.addEventListener('focus', handleWindowFocus);
        }

        // 输入变化处理
        function handleInputChange() {
            adjustInputHeight();
            updateCharCounter();
        }
        
        // 表单提交处理
        function handleSubmit(e) {
            e.preventDefault();
            sendMessage();
        }
        
        // 窗口焦点变化处理
        function handleWindowFocus() {
            if (Date.now() - lastFetchTime > 5000) {
                fetchMessages();
            }
        }

        // 调整输入框高度
        function adjustInputHeight() {
            messageInput.style.height = 'auto';
            messageInput.style.height = Math.min(messageInput.scrollHeight, 150) + 'px';
        }

        // 更新字符计数器
        function updateCharCounter() {
            const length = messageInput.value.length;
            charCounter.textContent = `${length}/2000`;
            charCounter.style.color = length > 2000 ? '#e74c3c' : '#718096';
            sendBtn.disabled = isSending || length === 0 || length > 2000;
        }

        // 初始化表情选择器
        function initEmojiPicker() {
            const EMOJIS = [
                "😀", "😃", "😄", "😁", "😆", "😅", "😂", "🤣", "😊", "😇",
                "🙂", "🙃", "😉", "😌", "😍", "🥰", "😘", "😗", "😙", "😚",
                "😋", "😛", "😝", "😜", "🤪", "🤨", "🧐", "🤓", "😎", "🤩",
                "🥳", "😏", "😒", "😞", "😔", "😟", "😕", "🙁", "☹️", "😣",
                "😖", "😫", "😩", "🥺", "😢", "😭", "😤", "😠", "😡", "🤬",
                "🤯", "😳", "🥵", "🥶", "😱", "😨", "😰", "😥", "😓", "🫣",
                "🤗", "🫡", "🤔", "🫢", "🤭", "🤫", "🤥", "😶", "🫠", "😑",
                "🫤", "😒", "🙄", "😬", "😮‍💨", "🤤", "😪", "😮", "😯", "😲",
                "🥱", "😵", "😵‍💫", "🤐", "🥴", "🤢", "🤮", "🤧", "😷", "🤒",
                "🤕", "🤑", "😈", "👿", "👹", "👺", "🤡", "💩", "👻", "💀",
                "☠️", "👽", "👾", "🤖", "🎃", "😺", "😸", "😹", "😻", "😼",
                "😽", "🙀", "😿", "😾", "❤️", "💘", "💝", "💖", "💗", "💕",
                "💞", "💓", "💔", "💋", "💐", "🌹", "🥀", "🌷", "🌼", "🌸",
                "🌺", "🌻", "🍕", "🍔", "🍟", "🍗", "🌭", "🍿", "🍦", "🍨",
                "🍩", "🍪", "🎂", "🍰", "🍫", "☕", "🍺", "🍷", "🍾", "🍹"
            ];
            
            emojiPicker.innerHTML = '';
            EMOJIS.forEach(emoji => {
                const emojiItem = document.createElement('div');
                emojiItem.className = 'emoji-item';
                emojiItem.textContent = emoji;
                emojiItem.addEventListener('click', () => insertEmoji(emoji));
                emojiPicker.appendChild(emojiItem);
            });
        }

        // 插入表情
        function insertEmoji(emoji) {
            messageInput.value += emoji;
            handleInputChange();
            toggleEmojiPicker();
        }

        // 切换表情选择器
        function toggleEmojiPicker() {
            isEmojiPickerOpen = !isEmojiPickerOpen;
            emojiPicker.style.display = isEmojiPickerOpen ? 'flex' : 'none';
        }

        // 图片预览
        function openPreview(src) {
            previewImage.src = src;
            preview.style.display = 'flex';
            toggleEmojiPicker(false);
        }

        function closePreview() {
            preview.style.display = 'none';
        }

        // 处理文档点击（关闭表情选择器）
        function handleDocumentClick(e) {
            if (isEmojiPickerOpen && !emojiPicker.contains(e.target) && e.target !== emojiBtn) {
                toggleEmojiPicker();
            }
        }

        // 处理滚动事件
        function handleScroll() {
            const isNearBottom = chatContainer.scrollTop + chatContainer.clientHeight >= chatContainer.scrollHeight - 50;
            isAtBottom = isNearBottom;
            scrollToBottomBtn.style.display = isAtBottom ? 'none' : 'flex';
        }

        // 滚动到底部
        function scrollToBottom() {
            chatContainer.scrollTop = chatContainer.scrollHeight;
            isAtBottom = true;
            scrollToBottomBtn.style.display = 'none';
        }

        // 获取消息
        function fetchMessages() {
            if (isLoading) return;
            
            isLoading = true;
            lastFetchTime = Date.now();
            
            // 获取消息时传递最后一条消息的时间戳
            const lastTimestamp = allMessages.length > 0 ? 
                new Date(allMessages[allMessages.length - 1].timestamp).getTime() : 0;
            
            fetch(`?id=${GROUP_ID}&fetch_messages=true`)
                .then(response => response.json())
                .then(serverMessages => {
                    if (loadingMessages) loadingMessages.style.display = 'none';
                    
                    // 筛选服务器中比客户端最新消息更新的消息
                    const newServerMessages = serverMessages.filter(msg => {
                        const msgTime = new Date(msg.timestamp).getTime();
                        return msgTime > lastTimestamp;
                    });
                    
                    // 处理新消息 - 替换临时消息
                    const messagesToRender = [];
                    let hasUpdates = false;
                    
                    newServerMessages.forEach(serverMsg => {
                        // 检查是否为匹配的临时消息
                        if (serverMsg.temp_id) {
                            const tempMsg = pendingTempMessages.get(serverMsg.temp_id);
                            if (tempMsg) {
                                // 找到对应的临时消息索引
                                const tempIndex = allMessages.findIndex(m => m.id === tempMsg.id);
                                if (tempIndex !== -1) {
                                    // 更新临时消息为服务器消息
                                    allMessages[tempIndex] = {
                                        ...serverMsg,
                                        // 保留临时消息的DOM ID以便更新
                                        domId: tempMsg.domId
                                    };
                                    
                                    // 更新消息缓存
                                    messageCache.set(serverMsg.id, allMessages[tempIndex]);
                                    
                                    // 更新DOM中的消息
                                    updateMessageElement(allMessages[tempIndex]);
                                    
                                    // 从待处理列表中移除
                                    pendingTempMessages.delete(serverMsg.temp_id);
                                    hasUpdates = true;
                                    return;
                                }
                            }
                        }
                        
                        // 检查消息是否已存在
                        if (messageCache.has(serverMsg.id)) {
                            // 消息已存在，跳过
                            return;
                        }
                        
                        // 添加到列表
                        allMessages.push(serverMsg);
                        messageCache.set(serverMsg.id, serverMsg);
                        messagesToRender.push(serverMsg);
                        hasUpdates = true;
                    });
                    
                    // 渲染新消息
                    if (messagesToRender.length > 0) {
                        renderMessages(messagesToRender);
                        
                        // 如果用户在最底部，自动滚动到底部
                        if (isAtBottom) {
                            scrollToBottom();
                        }
                    }
                    
                    // 清理失败或长时间未确认的临时消息（超过10秒）
                    const now = Date.now();
                    pendingTempMessages.forEach((tempMsg, tempId) => {
                        if (now - new Date(tempMsg.timestamp).getTime() > 10000) {
                            // 标记为失败
                            tempMsg.status = 'failed';
                            const tempIndex = allMessages.findIndex(m => m.id === tempMsg.id);
                            if (tempIndex !== -1) {
                                allMessages[tempIndex] = {...tempMsg};
                                updateMessageElement(tempMsg);
                            }
                        }
                    });
                    
                    // 如果有更新，重置发送状态
                    if (hasUpdates) {
                        setSendingState(false);
                    }
                })
                .catch(error => {
                    console.error('获取消息失败:', error);
                })
                .finally(() => {
                    isLoading = false;
                    
                    // 设置下一次定时刷新
                    if (document.visibilityState === 'visible') {
                        setTimeout(fetchMessages, 2000);
                    }
                });
        }

        // 更新消息元素
        function updateMessageElement(msg) {
            if (!msg.domId) return;
            
            const messageElement = document.getElementById(msg.domId);
            if (!messageElement) return;
            
            const isCurrentUser = msg.sender === CURRENT_USER;
            
            // 更新消息内容
            const contentElement = messageElement.querySelector('.message-content');
            if (contentElement) {
                contentElement.innerHTML = '';
                
                if (msg.type === 'image') {
                    const img = document.createElement('img');
                    img.className = 'message-image';
                    img.src = msg.content;
                    img.alt = '群聊图片';
                    img.onclick = () => openPreview(msg.content);
                    contentElement.appendChild(img);
                } else {
                    const text = document.createElement('div');
                    text.textContent = msg.content;
                    contentElement.appendChild(text);
                }
            }
            
            // 更新消息状态
            const statusElement = messageElement.querySelector('.message-status');
            if (statusElement) {
                if (msg.status === 'sending') {
                    statusElement.innerHTML = '<i class="fas fa-circle-notch fa-spin"></i> 发送中';
                } else if (msg.status === 'failed') {
                    statusElement.innerHTML = `
                        <i class="fas fa-exclamation-triangle"></i> 发送失败
                        <button class="retry-btn" onclick="retryMessage('${msg.id}')">重发</button>
                    `;
                } else {
                    statusElement.remove();
                }
            }
            
            // 更新时间戳
            const timestampElement = messageElement.querySelector('.timestamp');
            if (timestampElement) {
                timestampElement.textContent = formatTimestamp(msg.timestamp);
            }
        }

        // 渲染消息
        function renderMessages(messagesToRender) {
            if (messagesToRender.length === 0 && allMessages.length === 0) {
                chatContainer.innerHTML = `
                    <div class="no-messages">
                        <i class="fas fa-comment-slash"></i>
                        <h3>暂无消息</h3>
                        <p>成为第一个发言的人吧！</p>
                    </div>
                `;
                return;
            }
            
            // 只渲染未渲染过的消息
            const newMessages = messagesToRender.filter(msg => !renderedMessageIds.has(msg.id));
            
            if (newMessages.length === 0) return;
            
            newMessages.forEach(msg => {
                // 检查消息是否已存在
                if (renderedMessageIds.has(msg.id)) return;
                
                renderedMessageIds.add(msg.id);
                const isCurrentUser = msg.sender === CURRENT_USER;
                const messageGroup = document.createElement('div');
                messageGroup.className = `message-group ${isCurrentUser ? 'current-user' : 'other-user'} fade-in`;
                
                // 为消息分配唯一DOM ID
                const domId = `msg-${Date.now()}-${Math.random().toString(36).substr(2, 5)}`;
                messageGroup.id = domId;
                msg.domId = domId;
                
                const container = document.createElement('div');
                container.className = 'message-container';
                
                // 头像 - 添加点击跳转功能
                const avatar = document.createElement('div');
                avatar.className = 'avatar';
                avatar.style.cursor = 'pointer';
                avatar.onclick = () => {
                    window.location.href = `userinfo.php?user=${encodeURIComponent(msg.sender)}`;
                };
                
                // 使用实际头像URL（如果存在）
                if (msg.avatar && msg.avatar !== 'default-avatar.png') {
                    const avatarImg = document.createElement('img');
                    avatarImg.src = msg.avatar;
                    avatarImg.alt = msg.sender.charAt(0);
                    avatarImg.style.width = '100%';
                    avatarImg.style.height = '100%';
                    avatarImg.style.borderRadius = '50%';
                    avatar.appendChild(avatarImg);
                } else {
                    // 使用首字母作为后备
                    avatar.textContent = msg.sender.charAt(0).toUpperCase();
                }
                
                // 消息内容容器
                const contentWrapper = document.createElement('div');
                contentWrapper.className = 'message-content-wrapper';
                
                // 消息头部（用户名和时间戳）
                const header = document.createElement('div');
                header.className = 'message-header';
                
               const username = document.createElement('div');
username.className = 'username';
username.innerHTML = `
    ${msg.sender}
    <div class="titles-container">${renderUserTitles(msg.sender)}</div>
`;

                
                const timestamp = document.createElement('div');
                timestamp.className = 'timestamp';
                timestamp.textContent = formatTimestamp(msg.timestamp);
                
                if (isCurrentUser) {
                    header.appendChild(timestamp);
                    header.appendChild(username);
                } else {
                    header.appendChild(username);
                    header.appendChild(timestamp);
                }
                
                // 消息内容
                const content = document.createElement('div');
                content.className = 'message-content';
                
                if (msg.type === 'image') {
                    const img = document.createElement('img');
                    img.className = 'message-image';
                    img.src = msg.content;
                    img.alt = '群聊图片';
                    img.onclick = () => openPreview(msg.content);
                    content.appendChild(img);
                } else {
                    const text = document.createElement('div');
                    text.textContent = msg.content;
                    content.appendChild(text);
                }
                
                // 添加消息状态（如果是当前用户的消息）
                if (isCurrentUser && msg.status) {
                    const status = document.createElement('div');
                    status.className = 'message-status';
                    
                    let statusHTML = '';
                    if (msg.status === 'sending') {
                        statusHTML = '<i class="fas fa-circle-notch fa-spin"></i> 发送中';
                    } else if (msg.status === 'failed') {
                        statusHTML = `
                            <i class="fas fa-exclamation-triangle"></i> 发送失败
                            <button class="retry-btn" onclick="retryMessage('${msg.id}')">重发</button>
                        `;
                    }
                    
                    status.innerHTML = statusHTML;
                    content.appendChild(status);
                }
                
                // 组装消息结构
                contentWrapper.appendChild(header);
                contentWrapper.appendChild(content);
                
                if (isCurrentUser) {
                    container.appendChild(contentWrapper);
                    container.appendChild(avatar);
                } else {
                    container.appendChild(avatar);
                    container.appendChild(contentWrapper);
                }
                
                messageGroup.appendChild(container);
                chatContainer.appendChild(messageGroup);
            });
            
            // 确保在每次渲染后滚动位置正确
            if (isAtBottom) {
                setTimeout(scrollToBottom, 10);
            }
        }

        // 格式化时间
        function formatTimestamp(timestamp) {
            const date = new Date(timestamp);
            const now = new Date();
            
            const diffHours = Math.floor((now - date) / 3600000);
            
            if (diffHours < 1) {
                // 一小时内显示分钟
                const diffMins = Math.floor((now - date) / 60000);
                return `${diffMins}分钟前`;
            } else if (date.toDateString() === now.toDateString()) {
                // 今天显示时间
                return date.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
            } else {
                // 其他时间显示日期
                return date.toLocaleDateString([], { month: 'short', day: 'numeric' });
            }
        }

        // 发送消息
        async function sendMessage() {
            // 防止重复发送
            if (isSending) return;
            
            const content = messageInput.value.trim();
            if (!content || content.length > 2000) return;
            
            // 创建唯一ID的临时消息
            const tempMsgId = `temp_${Date.now()}_${Math.random().toString(36).substr(2, 5)}`;
            const tempMsg = {
                id: tempMsgId,
                sender: CURRENT_USER,
                avatar: USER_AVATAR,
                content: content,
                type: 'text',
                timestamp: new Date().toISOString(),
                status: 'sending',
                temp_id: tempMsgId  // 用于服务器匹配
            };
            
            try {
                setSendingState(true);
                
                // 添加到消息列表并渲染
                allMessages.push(tempMsg);
                pendingTempMessages.set(tempMsgId, tempMsg);
                messageCache.set(tempMsgId, tempMsg);
                renderMessages([tempMsg]);
                scrollToBottom();
                
                // 重置输入框
                messageInput.value = '';
                handleInputChange();
                
                // 发送请求
                const response = await fetch('', {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
                    body: new URLSearchParams({
                        action: 'send_message',
                        message: content,
                        temp_id: tempMsgId  // 添加临时ID用于服务器匹配
                    })
                });
                
                const result = await response.json();
                
                if (result.status !== 'success') {
                    throw new Error('发送失败');
                }
                
            } catch (error) {
                console.error('发送消息失败:', error);
                // 标记临时消息为失败
                const tempMessage = pendingTempMessages.get(tempMsgId);
                if (tempMessage) {
                    tempMessage.status = 'failed';
                    const tempIndex = allMessages.findIndex(m => m.id === tempMsgId);
                    if (tempIndex !== -1) {
                        allMessages[tempIndex] = {...tempMessage};
                        updateMessageElement(tempMessage);
                    }
                }
                setSendingState(false);
            }
        }

        // 发送图片
        async function sendImage(e) {
            if (isSending || !e.target.files.length) return;
            
            const file = e.target.files[0];
            if (!file.type.match('image.*')) {
                alert('请选择图片文件');
                return;
            }
            
            // 创建唯一ID的临时消息
            const tempMsgId = `img_${Date.now()}_${Math.random().toString(36).substr(2, 5)}`;
            const tempMsg = {
                id: tempMsgId,
                sender: CURRENT_USER,
                avatar: USER_AVATAR,
                content: URL.createObjectURL(file),
                type: 'image',
                timestamp: new Date().toISOString(),
                status: 'sending',
                temp_id: tempMsgId  // 用于服务器匹配
            };
            
            try {
                setSendingState(true);
                
                // 添加到消息列表并渲染
                allMessages.push(tempMsg);
                pendingTempMessages.set(tempMsgId, tempMsg);
                messageCache.set(tempMsgId, tempMsg);
                renderMessages([tempMsg]);
                scrollToBottom();
                
                // 发送请求
                const formData = new FormData();
                formData.append('action', 'send_image');
                formData.append('image', file);
                formData.append('temp_id', tempMsgId);  // 添加临时ID用于服务器匹配
                
                const response = await fetch('', {
                    method: 'POST',
                    body: formData
                });
                
                const result = await response.json();
                
                if (result.status !== 'success') {
                    throw new Error('发送失败');
                }
            } catch (error) {
                console.error('发送图片失败:', error);
                // 标记临时消息为失败
                const tempMessage = pendingTempMessages.get(tempMsgId);
                if (tempMessage) {
                    tempMessage.status = 'failed';
                    const tempIndex = allMessages.findIndex(m => m.id === tempMsgId);
                    if (tempIndex !== -1) {
                        allMessages[tempIndex] = {...tempMessage};
                        updateMessageElement(tempMessage);
                    }
                }
                setSendingState(false);
            } finally {
                e.target.value = '';
            }
        }

        // 重发消息
        async function retryMessage(messageId) {
            if (isSending) return;
            
            try {
                setSendingState(true);
                
                // 查找要重发的消息
                const messageToResend = allMessages.find(msg => msg.id === messageId);
                if (!messageToResend) return;
                
                // 更新状态为发送中
                messageToResend.status = 'sending';
                const msgIndex = allMessages.findIndex(msg => msg.id === messageId);
                if (msgIndex !== -1) {
                    allMessages[msgIndex] = {...messageToResend};
                    updateMessageElement(messageToResend);
                }
                
                // 根据消息类型重新发送
                if (messageToResend.type === 'image') {
                    // 重新发送图片需要特殊处理
                    const response = await fetch('', {
                        method: 'POST',
                        headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
                        body: new URLSearchParams({
                            action: 'retry_message',
                            message_id: messageToResend.id
                        })
                    });
                    
                    const result = await response.json();
                    
                    if (result.status !== 'success') {
                        throw new Error('重发失败');
                    }
                } else {
                    // 重新发送文本消息
                    const response = await fetch('', {
                        method: 'POST',
                        headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
                        body: new URLSearchParams({
                            action: 'send_message',
                            message: messageToResend.content,
                            temp_id: messageToResend.id  // 使用原始ID作为临时ID
                        })
                    });
                    
                    const result = await response.json();
                    
                    if (result.status !== 'success') {
                        throw new Error('重发失败');
                    }
                }
            } catch (error) {
                console.error('重发消息失败:', error);
                messageToResend.status = 'failed';
                const failedIndex = allMessages.findIndex(msg => msg.id === messageId);
                if (failedIndex !== -1) {
                    allMessages[failedIndex] = {...messageToResend};
                    updateMessageElement(messageToResend);
                }
                setSendingState(false);
            }
        }

        // 设置发送状态
        function setSendingState(sending) {
            isSending = sending;
            if (sending) {
                sendBtn.innerHTML = '<i class="fas fa-spinner fa-spin"></i>';
                sendBtn.disabled = true;
                messageInput.disabled = true;
                imageBtn.disabled = true;
                emojiBtn.disabled = true;
            } else {
                sendBtn.innerHTML = '<i class="fas fa-paper-plane"></i>';
                sendBtn.disabled = false;
                messageInput.disabled = false;
                imageBtn.disabled = false;
                emojiBtn.disabled = false;
                updateCharCounter();
                messageInput.focus();
            }
        }
        

        // 初始化
        document.addEventListener('DOMContentLoaded', init);
    <?php endif; ?>

   // 修改后的退出群聊函数
function leaveGroup() {
    if (confirm('确定要退出这个群聊吗？此操作不可撤销。')) {
        // 发送POST请求到服务器端处理退出群聊
        fetch('leave_group.php', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded'
            },
            body: new URLSearchParams({
                group_id: GROUP_ID,
                user: CURRENT_USER
            })
        })
        .then(response => response.json())
        .then(data => {
            if (data.status === 'success') {
                alert(`已成功退出群聊: ${GROUP_NAME}`);
                location.href = 'index.php';
            } else {
                throw new Error(data.message || '退出群聊失败');
            }
        })
        .catch(error => {
            console.error('退出群聊错误:', error);
            alert('退出群聊失败: ' + error.message);
        });
    }
}
// 渲染用户称号
function renderUserTitles(username) {
    // 检查用户是否有称号
    if (!window.userTitles || !window.userTitles[username]) {
        return '';
    }
    
    const titles = window.userTitles[username];
    let html = '';
    
    titles.forEach(title => {
        html += `<span class="user-title" style="background: ${title.color}">${title.name}</span>`;
    });
    
    return html;
}
window.userTitles = <?= json_encode($allTitles) ?>;
</script>
</body>
</html>